package codetop.bytedance.T695;

/**
 * @Author: 18362
 * @Create: 2022-09-17 21:26:12 星期六
 */
class Solution {

    private int maxArea = 0;
    private int area;
    private int[][] grid;
    private int m;
    private int n;

    private static int[] dx = new int[] {-1, 1, 0, 0};
    private static int[] dy = new int[] {0, 0, -1, 1};

    public int maxAreaOfIsland(int[][] grid) {
        this.grid = grid;
        m = grid.length;
        n = grid[0].length;
        boolean[][] vis = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && !vis[i][j]) {
                    area = 0;
                    dfs(vis, i, j);
                }
            }
        }
        return maxArea;
    }

    private void dfs(boolean[][] vis, int x, int y) {
        vis[x][y] = true;
        area++;
        maxArea = Math.max(maxArea, area);
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx < 0 || ny < 0 || nx >= m || ny >= n || vis[nx][ny] || grid[nx][ny] == 0)
                continue;
            dfs(vis, nx, ny);
        }
    }
}